﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Model.Twitter;

namespace TwKarma.Data.Entity
{
	[Table]
	public class Tweet : TableBase
	{
        [PrimaryKey]
        public long StatusId { get; set; }

        [Field]
        public int FromId { get; set; }

        [Field(Size=200)]
        public string Text { get; set; }

		[Field]
		public DateTime When { get; set; }

        public static Tweet Get(long statusId)
        {
            using (TableAdapter<Tweet> adapter = TableAdapter<Tweet>.Open())
            {
                Tweet find = adapter.Read(statusId);
                if (find == null)
                {
                    TwitterResult result = Dimebrain.TweetSharp.Fluent.FluentTwitter.CreateRequest().Statuses().Show(statusId).AsJson().Request();
                    if (result.IsTwitterError)
                        return null;

                    var tweetStatus = result.AsStatus();
                    find =new Tweet() { StatusId = statusId, Text = tweetStatus.Text, When = tweetStatus.CreatedDate, FromId = tweetStatus.User.Id};

                    adapter.CreateUpdate(find);
                }

                return find;
            }
        }
	}
}